package cn.movie.types.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.stereotype.Repository;

import cn.movie.types.dao.ITypesDao;

@Repository("typesDao")
public class TypesDaoImpl implements ITypesDao {
	@Resource
	private DataSource dataSource;
	/* 
	 * @see cn.movie.types.dao.impl.ITypesDao#queryTypes()
	 */
	@Override
	public Map<String, Object> queryTypes() {
		MappingSqlQuery<Map<String, Long>> query = new MappingSqlQuery<Map<String, Long>>() {
			// mapRow()回调，每一行执行一次
			@Override
			protected Map<String, Long> mapRow(ResultSet rs, int rowNum) throws SQLException {
				Map<String, Long> map = new HashMap<>();
				map.put(rs.getString("type"), rs.getLong("cnt"));
				return map;
			}
		};

		query.setDataSource(dataSource);
		String sql = "select type,count(type) as cnt from movie group by type";
		query.setSql(sql);
		List<Map<String, Long>> list = query.execute();
		System.out.println("list:" + list);

		// 以下用于返回map
		List<String> xAxis = new ArrayList<>();
		List<Object> value = new ArrayList<>();
		for (Map<String, Long> map : list) {
			Map.Entry<String, Long> entry = map.entrySet().iterator().next();
			xAxis.add(entry.getKey());
			value.add(entry.getValue());
		}
		Map<String, Object> map = new HashMap<>();
		map.put("xAxis", xAxis);
		map.put("value", value);
		System.out.println("map:"+map.toString());
		return map;

	}
}
